<!-- pages/questionManage/questionManage.vue -->
<template>
  <view class="question-manage-container">
    <!-- 操作栏 -->
    <view class="operation-bar">
      <uni-search-bar 
        placeholder="搜索题目内容" 
        v-model="searchKey"
        @confirm="loadData(true)"
        cancel-button="none"
      />
      <view class="filter-row">
        <button class="add-btn" @tap="showEditForm(null)">+ 新建题目</button>
      </view>
    </view>

    <!-- 统计信息 -->
    <view class="stats-container">
      <view class="stat-card">
        <text class="stat-value">{{ total }}</text>
        <text class="stat-label">总题数</text>
      </view>
     <!-- <view class="stat-card">
        <text class="stat-value">{{ activeCount }}</text>
        <text class="stat-label">启用中</text>
      </view> -->
    </view>

    <!-- 题目列表 -->
    <scroll-view 
      class="question-list"
      scroll-y
      @scrolltolower="loadMore"
    >
      <view 
        v-for="(question, index) in showList"
        :key="index"
        class="question-card"
      >
        <view class="card-header">
          <uni-tag 
            text="单选题"
            type="primary"
            size="small"
          />
        </view>

        <view class="card-body">
          <text class="question-text">{{ question.text }}</text>
          
          <view class="options-container">
            <view 
              v-for="(option, oIndex) in question.options"
              :key="oIndex"
              class="option-item"
              :class="{ correct: isCorrectAnswer(question, option) }"
            >
              <text class="option-index">
                {{ String.fromCharCode(65 + oIndex) }}.
              </text>
              <text class="option-content">{{ option }}</text>
            </view>
          </view>
        </view>

        <view class="card-footer">
          <text class="create-time">创建时间：{{ question.createTime | formatTime }}</text>
          <view class="action-btns">
            <button class="btn edit" @tap="showEditForm(question)">编辑</button>
          </view>
        </view>
      </view>

      <uni-load-more :status="loadingStatus"/>
    </scroll-view>

    <!-- 编辑弹窗 -->
    <uni-popup ref="editPopup" type="dialog">
      <uni-popup-dialog 
        mode="form" 
        :title="editForm.id ? '编辑题目' : '新建题目'"
        @confirm="submitForm"
        @close="resetForm"
      >
        <uni-forms :model="editForm" ref="formRef" :rules="rules">
          <uni-forms-item label="题目内容" required name="text">
            <uni-easyinput
              type="textarea"
              v-model="editForm.text"
              placeholder="请输入题目内容"
              :inputBorder="false"
            />
          </uni-forms-item>

          <uni-forms-item 
            label="题目选项" 
            required 
            name="options"
          >
            <view class="option-editor">
              <view 
                v-for="(_, index) in 4"
                :key="index"
                class="option-row"
              >
                <text class="option-label">{{ String.fromCharCode(65 + index) }}.</text>
                <uni-easyinput
                  v-model="editForm.options[index]"
                  placeholder="请输入选项内容"
                />
              </view>
            </view>
          </uni-forms-item>

          <uni-forms-item label="正确答案" required name="answer">
            <radio-group>
              <view 
                v-for="(option, index) in editForm.options"
                :key="index"
                class="radio-item"
              >
                <radio 
                  :value="option"
                  :checked="editForm.answer === option"
                  @click="editForm.answer = option"
                />
                <text class="option-text">{{ String.fromCharCode(65 + index) }}. {{ option }}</text>
              </view>
            </radio-group>
          </uni-forms-item>
        </uni-forms>
      </uni-popup-dialog>
    </uni-popup>
  </view>
</template>

<script>


export default {
  data() {
    return {
      searchKey: '',
      loadingStatus: 'more',
      page: 1,
      pageSize: 10,
      total: 0,
      activeCount: 0,
      questionList: [],
      editForm: this.getDefaultForm(),
      rules: {
        text: {
          rules: [{
            required: true,
            errorMessage: '题目内容不能为空'
          }]
        },
        options: {
          rules: [{
            validate: (value) => value.every(opt => opt.trim()),
            errorMessage: '请填写所有选项内容'
          }]
        },
        answer: {
          rules: [{
            required: true,
            errorMessage: '请选择正确答案'
          }]
        }
      }
    }
  },
  filters: {
    formatTime(timestamp) {
      const date = new Date(timestamp)
      return `${date.getFullYear()}-${(date.getMonth()+1).toString().padStart(2,'0')}-${date.getDate().toString().padStart(2,'0')}`
    }
  },
  computed: {
    showList() {
      return this.questionList.filter(q => {
        const questionText = (q.text || '').toString().toLowerCase()
        const searchKey = (this.searchKey || '').toString().toLowerCase()
        return questionText.includes(searchKey)
      })
    }
  },
  onLoad() {
    this.loadData()
  },
  methods: {
    showEditForm(question) {
      if (question) {
        this.editForm = {
          id: question.id,
          text: question.text,
          options: [...question.options],
          answer: question.answer,
          status: question.status
        }
      } else {
        this.editForm = this.getDefaultForm()
      }
      this.$refs.editPopup.open()
    },
    async loadData(reset = false) {
      if (reset) {
        this.page = 1
        this.questionList = []
      }

      this.loadingStatus = 'loading'
      
      try {
        const res = await uniCloud.callFunction({
          name: 'getQuestionsManage',
          data: {
            searchKey: this.searchKey,
            page: this.page,
            pageSize: this.pageSize
          }
        })

        if (res.result.code === 0) {
          const validList = res.result.data.list.filter(item => !!item.text)
          this.questionList = reset ? validList : [...this.questionList, ...validList]
          this.total = res.result.data.total
          this.activeCount = this.questionList.filter(q => q.status).length
          this.loadingStatus = res.result.data.list.length < this.pageSize ? 'noMore' : 'more'
        }
      } catch (e) {
        uni.showToast({ title: '数据加载失败', icon: 'none' })
        this.loadingStatus = 'more'
      }
    },
    getDefaultForm() {
      return {
        id: null,
        text: '',
        options: ['', '', '', ''],
        answer: '',
        status: true
      }
    },
    isCorrectAnswer(question, option) {
      return question.answer === option
    },
    async submitForm() {
      try {
        await this.$refs.formRef.validate()
        if (!await this.validateForm()) return

        const dbData = {
          text: this.editForm.text,
          options: this.editForm.options.map(opt => opt.trim()),
          answer: this.editForm.answer,
          status: this.editForm.status,
        }

        if (this.editForm.id) {
          const res = await uniCloud.callFunction({
            name: 'updateQuestion',
            data: {
              id: this.editForm.id,
              questionData: dbData
            }
          })
          if (res.result.code !== 0) throw new Error(res.result.msg)
        } else {
          const res = await uniCloud.callFunction({
              name: 'createQuestion',
              data: {
                questionData: dbData
              }
            })
            if (res.result.code !== 0) throw new Error(res.result.msg)
        }
        
        uni.showToast({ title: '操作成功' })
        this.loadData(true)
        this.$refs.editPopup.close()
      } catch (e) {
        uni.showToast({ 
          title: this.getErrorMessage(e), 
          icon: 'none',
          duration: 3000 
        })
      }
    },
    getErrorMessage(e) {
      const errorMap = {
        'invalid document id': '题目不存在',
        'DATABASE_COLLECTION_DENIED': '没有操作权限',
        'PERMISSION_DENIED': '权限不足'
      }
      return errorMap[e.message] || e.message || '操作失败，请重试'
    },
    async validateForm() {
      const validOptions = this.editForm.options
        .map(opt => opt.trim())
        .filter(opt => opt !== '')
      
      if (validOptions.length < 2) {
        uni.showToast({ title: '至少需要2个有效选项', icon: 'none' })
        return false
      }
      
      if (!validOptions.includes(this.editForm.answer)) {
        uni.showToast({ title: '答案必须存在于选项中', icon: 'none' })
        return false
      }
      
      return true
    }
  }
}
</script>

<style lang="scss" scoped>
.question-manage-container {
  padding: 24rpx;
  background: #f5f7fa;
  min-height: 100vh;
}

.operation-bar {
  background: white;
  padding: 24rpx;
  border-radius: 16rpx;
  margin-bottom: 24rpx;
  box-shadow: 0 2rpx 12rpx rgba(0,0,0,0.05);

  .filter-row {
    display: flex;
    justify-content: flex-end;
    margin-top: 24rpx;

    .add-btn {
      background: #3498db;
      color: white;
      padding: 0 32rpx;
      border-radius: 8rpx;
      font-size: 28rpx;
      line-height: 2;
    }
  }
}

.stats-container {
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  gap: 24rpx;
  margin-bottom: 32rpx;

  .stat-card {
    background: white;
    padding: 32rpx;
    border-radius: 16rpx;
    text-align: center;
    width: 600rpx;
    margin-left: 20rpx;

    .stat-value {
      font-size: 40rpx;
      font-weight: bold;
      color: #2ecc71;
      display: block;
      margin-bottom: 8rpx;
    }

    .stat-label {
      font-size: 26rpx;
      color: #7f8c8d;
    }
  }
}

.question-card {
  background: white;
  border-radius: 16rpx;
  margin-bottom: 24rpx;
  padding: 24rpx;
  box-shadow: 0 2rpx 8rpx rgba(0,0,0,0.05);

  .card-header {
    margin-bottom: 24rpx;
  }

  .question-text {
    font-size: 30rpx;
    color: #34495e;
    line-height: 1.6;
    margin-bottom: 24rpx;
  }

  .options-container {
    display: grid;
    grid-template-columns: repeat(2, 1fr);
    gap: 16rpx;

    .option-item {
      padding: 20rpx;
      border-radius: 12rpx;
      background: #f8f9fa;
      min-height: 100rpx;

      &.correct {
        background: #e8f6f3;
        border: 2rpx solid #2ecc71;
      }

      .option-index {
        color: #3498db;
        margin-right: 8rpx;
        font-weight: bold;
      }
    }
  }

  .card-footer {
    margin-top: 24rpx;
    padding-top: 24rpx;
    border-top: 1rpx solid #eee;

    .create-time {
      font-size: 24rpx;
      color: #95a5a6;
    }

    .action-btns {
      display: flex;
      gap: 16rpx;
      margin-top: 16rpx;

      .btn {
        flex: 1;
        padding: 12rpx;
        border-radius: 8rpx;
        font-size: 26rpx;

        &.edit { background: #f1c40f; color: white; }
      }
    }
  }
}

.option-editor {
  .option-row {
    display: flex;
    align-items: center;
    gap: 16rpx;
    margin-bottom: 16rpx;

    .option-label {
      width: 60rpx;
      font-weight: bold;
    }
  }
}

.radio-item {
  display: flex;
  align-items: center;
  padding: 16rpx;
  margin: 8rpx 0;
  border-radius: 8rpx;
  background: #f8f9fa;

  radio {
    transform: scale(0.9);
    margin-right: 12rpx;
  }
}
</style>